package com.sheyu.mall.seckill.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.sheyu.common.to.SeckillOrderTo;
import com.sheyu.common.utils.R;
import com.sheyu.common.vo.MemberResponseVo;
import com.sheyu.mall.seckill.feignService.CouponFeignService;
import com.sheyu.mall.seckill.feignService.ProductFeignService;
import com.sheyu.mall.seckill.interceptor.LoginUserInterceptor;
import com.sheyu.mall.seckill.service.SeckillService;
import com.sheyu.mall.seckill.to.SeckillSkuRedisTo;
import com.sheyu.mall.seckill.vo.SeckillSessionWithSkusVo;
import com.sheyu.mall.seckill.vo.SkuInfoVo;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * @author sheyu
 * @Desciption:
 * @date 2020/9/24 5:41 下午
 */
@Service
@Slf4j
public class SeckillServiceImpl implements SeckillService {

    @Autowired
    private CouponFeignService couponFeignService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    ProductFeignService productFeignService;

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Autowired
    RedissonClient redissonClient;

    private final String SESSION__CACHE_PREFIX = "seckill:sessions:";

    private final String SECKILL_CHARE_PREFIX = "seckill:skus";

    private final String SKU_STOCK_SEMAPHORE = "seckill:stock:";


    /**
     * 上架三天需要秒杀的商品
     */
    @Override
    public void uploadSeckillSkuLatest3Days() {
        //1、扫描最近三天的商品需要参加秒杀的活动
        R r =  couponFeignService.getLates3DaySession();
        if (r.getCode()==0){
            List<SeckillSessionWithSkusVo> seckillSessionWithSkusVos =
                    r.getData("data",new TypeReference<List<SeckillSessionWithSkusVo>>(){});
            //缓存到Redis
            //1、缓存活动信息
            saveSessionInfos(seckillSessionWithSkusVos);

            //2、缓存活动的关联商品信息

            saveSessionSkuInfo(seckillSessionWithSkusVos);
        }
    }

    private void saveSessionSkuInfo(List<SeckillSessionWithSkusVo> seckillSessionWithSkusVos) {
        seckillSessionWithSkusVos.stream().forEach(seckillSessionWithSkusVo -> {

            //准备hash操作，绑定hash
            BoundHashOperations<String,Object,Object> operations = redisTemplate.boundHashOps(SECKILL_CHARE_PREFIX);

            seckillSessionWithSkusVo.getSeckillSkuRelationVos().stream().forEach(item->{
                String token = UUID.randomUUID().toString().replace("-,","");
                String redisKey = item.getPromotionSessionId().toString() + "-" + item.getSkuId().toString();
                if (!operations.hasKey(redisKey)){
                    //缓存商品信息
                    SeckillSkuRedisTo seckillSkuRedisTo = new SeckillSkuRedisTo();
                    Long skuId = item.getSkuId();

                    //查询sku的基本信息
                    R skuInfo = productFeignService.info(skuId);
                    if (skuInfo.getCode()==0){
                        SkuInfoVo skuInfoVo = skuInfo.getData("skuInfo",new TypeReference<SkuInfoVo>(){});
                        seckillSkuRedisTo.setSkuInfo(skuInfoVo);
                    }

                    //2、sku秒杀信息
                    BeanUtils.copyProperties(item,seckillSkuRedisTo);

                    //3、设置当前商品的秒杀时间信息
                    seckillSkuRedisTo.setStartTime(seckillSessionWithSkusVo.getStartTime().getTime());
                    seckillSkuRedisTo.setEndTime(seckillSessionWithSkusVo.getEndTime().getTime());

                    //设置商品的随机码
                    seckillSkuRedisTo.setRandomCode(token);

                    //序列化json格式存入redis中
                    String seckillValue = JSON.toJSONString(seckillSkuRedisTo);

                    operations.put(item.getPromotionSessionId().toString()+"-"+item.getSkuId().toString(),seckillValue);

                    //5、使用库存作为分布式信号量（限流）
                    //使用库存作为分布式信号量
                    RSemaphore rSemaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE + token);
                    //商品可以秒杀的数量作为信号量
                    rSemaphore.trySetPermits(item.getSeckillCount());
                }
            });
        });
    }

    private void saveSessionInfos(List<SeckillSessionWithSkusVo> seckillSessionWithSkusVos) {
        seckillSessionWithSkusVos.stream().forEach(seckillSessionWithSkusVo -> {
            long startTime = seckillSessionWithSkusVo.getStartTime().getTime();
            long endTime = seckillSessionWithSkusVo.getEndTime().getTime();

            //存入到redis中的key
            String key = SESSION__CACHE_PREFIX + startTime +"_"+ endTime;
            boolean hasKey = redisTemplate.hasKey(key);
            if (!hasKey){
                List<String> skuIds = seckillSessionWithSkusVo.getSeckillSkuRelationVos().stream().map(item->
                    item.getPromotionSessionId()+"-"+item.getSkuId().toString()
                ).collect(Collectors.toList());
                redisTemplate.opsForList().leftPushAll(key,skuIds);
            }
        });
    }

    @Override
    public List<SeckillSkuRedisTo> getCurrentSeckillSkus() {

        Set<String> keys = redisTemplate.keys(SESSION__CACHE_PREFIX + "*");
        for (String key:keys){
            String replaceWord = key.replace(SESSION__CACHE_PREFIX,"");
            String[] times = replaceWord.split("_");

            long startTime = Long.parseLong(times[0]);
            long endTime = Long.parseLong(times[1]);

            long currentTime = System.currentTimeMillis();
            if (currentTime>=startTime && currentTime<=endTime){
                //2、获取这个秒杀场景的所有商品
                List<String> range = redisTemplate.opsForList().range(key,-100,100);
                BoundHashOperations<String,String,String> hashOperations = redisTemplate.boundHashOps(SECKILL_CHARE_PREFIX);
                assert range != null;
                List<String> listValue = hashOperations.multiGet(range);
                if (listValue!=null&&listValue.size()>0){
                    List<SeckillSkuRedisTo> redisTos = listValue.stream().map(item->{
                        String items = (String)item;
                        SeckillSkuRedisTo seckillSkuRedisTo = JSON.parseObject(items,SeckillSkuRedisTo.class);
                        return seckillSkuRedisTo;
                    }).collect(Collectors.toList());
                    return redisTos;
                }
                break;
            }
        }
        return null;
    }

    /**
     * 根据skuId查询商品是否参加秒杀活动
     *
     * @param skuId
     * @return
     */
    @Override
    public SeckillSkuRedisTo getSkuSeckilInfo(Long skuId) {
        BoundHashOperations<String,String,String> hashOperations = redisTemplate.boundHashOps(SECKILL_CHARE_PREFIX);
        Set<String> keys = hashOperations.keys();
        for (String key:keys){
            String reg = "\\d-"+skuId;
            if (Pattern.matches(reg,key)){
                String redisValue = hashOperations.get(key);

                SeckillSkuRedisTo seckillSkuRedisTo = JSON.parseObject(redisValue,SeckillSkuRedisTo.class);

                //随机码
                //当前时间大于等于秒杀活动开始的时间并且小于活动结束的时间
                long currentTime = System.currentTimeMillis();
                long startTime = seckillSkuRedisTo.getStartTime();
                long endTime = seckillSkuRedisTo.getEndTime();
                if (currentTime>=startTime && currentTime<=endTime){
                    return seckillSkuRedisTo;
                }
                //随机码为null，就是不在这个秒杀活动中
                seckillSkuRedisTo.setRandomCode(null);
                return seckillSkuRedisTo;
            }
        }
        return null;
    }

    @Override
    public String kill(String killId, String key, Integer num) throws InterruptedException {


        long s1 = System.currentTimeMillis();
        //1、检查用户是否登陆,主要依靠interceptor,拦截器
        MemberResponseVo memberResponseVo = LoginUserInterceptor.loginUser.get();

        BoundHashOperations<String,String,String> hashOperations = redisTemplate.boundHashOps(SECKILL_CHARE_PREFIX);

        //是否存在对应场次的商品
        if (hashOperations.hasKey(killId)){
            String seckillSkuRedisToString = hashOperations.get(killId);
            SeckillSkuRedisTo seckillSkuRedisTo = JSON.parseObject(seckillSkuRedisToString,SeckillSkuRedisTo.class);
            long startTime = seckillSkuRedisTo.getStartTime();
            long endTime = seckillSkuRedisTo.getEndTime();
            long currentTime = System.currentTimeMillis();
            //是否在对应的时间内
            if (currentTime>=startTime && currentTime<=endTime){
                String randomCode = seckillSkuRedisTo.getRandomCode();

                String redisKeyOfSkuId = seckillSkuRedisTo.getPromotionSessionId() + "-" + seckillSkuRedisTo.getSkuId();
                if (randomCode.equals(key) && redisKeyOfSkuId.equals(killId)){

                    //获取sku的库存
                    Integer seckillLimit = seckillSkuRedisTo.getSeckillLimit();

                    //将库存变成信号量
                    String seckillCount = redisTemplate.opsForValue().get(SKU_STOCK_SEMAPHORE+randomCode);

                    Integer count = Integer.parseInt(seckillCount);

                    if (count > 0 && num <= seckillLimit && count > num){
                        String redisKey = memberResponseVo.getId() +"-"+ redisKeyOfSkuId;
                        //设置自动过期时间（活动结束时间-当前时间）
                        Long ttl = endTime - currentTime;
                        Boolean aBoolean = redisTemplate.opsForValue().setIfAbsent(redisKey, num.toString(), ttl, TimeUnit.MILLISECONDS);
                        if (aBoolean){
                            RSemaphore rSemaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE + randomCode);
                            boolean semaphoreCount = rSemaphore.tryAcquire(num);
                            if (semaphoreCount){
                                //创建订单号及订单，发送消息给MQ
                                //秒杀成功 快速下单 发送消息到MQ 整个操作时间在10ms左右

                                SeckillOrderTo orderTo = new SeckillOrderTo();

                                String timeId = IdWorker.getTimeId();
                                orderTo.setOrderSn(timeId);
                                orderTo.setMemberId(memberResponseVo.getId());
                                orderTo.setNum(num);
                                orderTo.setPromotionSessionId(seckillSkuRedisTo.getPromotionSessionId());
                                orderTo.setSkuId(seckillSkuRedisTo.getSkuId());
                                orderTo.setSeckillPrice(seckillSkuRedisTo.getSeckillPrice());

                                rabbitTemplate.convertAndSend("order-event-exchange",
                                        "order.seckill.order",orderTo);

                                long s2 = System.currentTimeMillis();
                                log.info("耗时..."+(s2-s1));
                                return timeId;
                            }
                        }
                    }
                }
            }
        }
        long s3 = System.currentTimeMillis();
        log.info("耗时..."+(s3-s1));
        return null;
    }

}
